import xmpp
from SIMPCore_pb2 import *
import thread
from time import sleep

XMPP_SERVERS = {'gmail.com':('talk.google.com', 5222)}

class XMPPClient:
	def __init__(self):
		self.m_jid = None;
		self.m_xmppclient = None;
		self.OnChatMessageRecievedHandler=0;
		pass
	def __del__(self):
		try:
			self.m_xmppclient.disconnect();
#self.m_xmppclient.disconnected();
		except Exception, e:
			print 'self.m_xmppclient.disconnected()===:', e

	def DisconnectHandler(self):
		print 'disconnect'
		
	def Login(self, req):
		self.m_jid = xmpp.JID(req.uid);
		self.m_xmppclient = xmpp.Client(self.m_jid.getDomain());
		self.m_xmppclient.connect(server=XMPP_SERVERS.get(self.m_jid.getDomain()));
		self.m_xmppclient.auth(self.m_jid.getNode(), req.password);
		self.m_xmppclient.sendInitPresence();

		rsp = MSG_Login_Rsp();
		rsp.rspcode=0;
		rsp.rspdesc='nothing';

		print 'login in.'

		self.m_xmppclient.RegisterDisconnectHandler(self.DisconnectHandler);

		return rsp;
	 
	def GetAllFriend(self, req):
		roster = self.m_xmppclient.getRoster();

		rsp = MSG_GetAllFriend_Rsp();
		friends = roster.getItems();
		for f in friends:
			rsp.frienduid.append(f);

		rsp.rspcode=0;
		rsp.rspdesc='nothing';

		print 'GetAllFriend:', friends

		return rsp;

	def SingleChat(self, req):

		print 'SingleChat() to[%s][%s]'%(req.dstuid, req.content)
		self.m_xmppclient.send(xmpp.Message(req.dstuid, req.content));
		rsp = MSG_SingleChat_Rsp();
		rsp.rspcode=0;
		rsp.rspdesc='nothing';

		return rsp;


